﻿using System;
using System.Collections.Concurrent;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace System {
    /// <summary>
    /// 配置帮助类
    /// </summary>
    public partial class ConfigurationHelper {
        /// <summary>
        /// 根据配置名称加载指定的配置项
        /// </summary>
        /// <param name="configFileName">配置文件名称，使用约定，配置文件放在项目的config目录中，如logging配置：config/logging.json</param>
        /// <param name="environmentName"></param>
        /// <param name="reloadOnChange">自动更新</param>
        /// <returns></returns>
        public IConfiguration Load(string configFileName,string environmentName = "",bool reloadOnChange = false) {
            var filePath = Path.Combine(AppContext.BaseDirectory,"config");
            if(!Directory.Exists(filePath))
                return null;

            var builder = new ConfigurationBuilder()
                .SetBasePath(filePath)
                .AddJsonFile(configFileName.ToLower() + ".json",true,reloadOnChange);

            if(environmentName.NotNull()) {
                builder.AddJsonFile(configFileName.ToLower() + "." + environmentName + ".json",true,reloadOnChange);
            }

            return builder.Build();
        }

        /// <summary>
        /// 根据配置名称加载指定的配置项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configFileName">配置文件名称，使用约定，配置文件放在项目的config目录中，如logging配置：config/logging.json</param>
        /// <param name="environmentName"></param>
        /// <param name="reloadOnChange">自动更新</param>
        /// <returns></returns>
        public T Get<T>(string configFileName,string environmentName = "",bool reloadOnChange = false) {
            var configuration = Load(configFileName,environmentName,reloadOnChange);
            if(configuration == null)
                return default;

            return configuration.Get<T>();
        }
    }
    public partial class ConfigurationHelper {
        /// <summary>
        /// 缓存数据（配置信息）
        /// </summary>
        private static readonly ConcurrentDictionary<string,object> _setting =
           new ConcurrentDictionary<string,object>();

        /// <summary>
        /// 设置信息
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetValue(string key,object value) {
            if(_setting.ContainsKey(key)) {
                _setting.TryRemove(key,out object result);
            }
            _setting.GetOrAdd(key,value);
        }
        /// <summary>
        /// 获取数据值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="key">键值</param>
        /// <returns></returns>
        public static T GetValue<T>(string key) where T : class {
            _setting.TryGetValue(key,out object result);
            return result as T;
        }
    }

}
